package com.hengpeng.itfin.persist.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.hengpeng.common.persist.AbstractDao;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.LockType;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.itfin.persist.InvestInfoDao;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.InvestInfo.InvestStatus;

@Repository
public class InvestInfoDaoImpl extends AbstractDao<InvestInfo> implements InvestInfoDao
{
	@Override
	public InvestInfo getInvestInfo(Long id, InvestStatus status)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		if (id != null)
		{
			query.eq("id", id);
		}
		if (status != null)
		{
			query.eq("status", status);
		}
		List<InvestInfo> list = super.findAllByDynamicQuery(query, InvestInfo.class);
		return list == null || list.size() < 1 ? null : list.get(0);
	}

	@Override
	public List<InvestInfo> queryList(Long borrowId, InvestStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		if (borrowId != null)
		{
			query.eq("borrowInfoId", borrowId);
		}
		if (status != null)
		{
			query.inArray("status", status);
		}
		return super.findAllByDynamicQuery(query, InvestInfo.class);
	}

	@Override
	public List<InvestInfo> lockList(Long borrowId, InvestStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		if (borrowId != null)
		{
			query.eq("borrowInfoId", borrowId);
		}
		if (status != null)
		{
			query.inArray("status", status);
		}
		return super.findAllByDynamicQuery(query, LockType.LOCK_WAIT);
	}

	@Override
	public long countByBorrowId(Long borrowId, InvestStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		query.eq("borrowInfoId", borrowId);
		if (status != null)
		{
			query.inArray("status", status);
		}
		query.addProjection(Projections.count());
		query.setQueryType(QueryType.JDBC);
		return super.countByDynamicQuery(query);
	}

	@Override
	public void saveList(List<InvestInfo> invests)
	{
		super.saveAll(invests);
	}

	@Override
	public void saveInvest(InvestInfo invest)
	{
		super.save(invest);
	}

	@Override
	public void updateInvest(InvestInfo invest)
	{
		super.update(invest);
	}

	@Override
	public void updateList(List<InvestInfo> invests)
	{
		super.updateAll(invests);
	}
}
